1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.io;
18  
19  import com.google.common.annotations.Beta;
20  
21  import java.io.Flushable;
22  import java.io.IOException;
23  import java.util.logging.Level;
24  import java.util.logging.Logger;
25  
26  /**
27   * Utility methods for working with {@link Flushable} objects.
28   *
29   * @author Michael Lancaster
30   * @since 1.0
31   */
32  @Beta
33  public final class Flushables {
34    private static final Logger logger
35        = Logger.getLogger(Flushables.class.getName());
36  
37    private Flushables() {}
38  
39    /**
40     * Flush a {@link Flushable}, with control over whether an
41     * {@code IOException} may be thrown.
42     *
43     * <p>If {@code swallowIOException} is true, then we don't rethrow
44     * {@code IOException}, but merely log it.
45     *
46     * @param flushable the {@code Flushable} object to be flushed.
47     * @param swallowIOException if true, don't propagate IO exceptions
48     *     thrown by the {@code flush} method
49     * @throws IOException if {@code swallowIOException} is false and
50     *     {@link Flushable#flush} throws an {@code IOException}.
51     * @see Closeables#close
52     */
53    public static void flush(Flushable flushable, boolean swallowIOException)
54        throws IOException {
55      try {
56        flushable.flush();
57      } catch (IOException e) {
58        if (swallowIOException) {
59          logger.log(Level.WARNING,
60              "IOException thrown while flushing Flushable.", e);
61        } else {
62          throw e;
63        }
64      }
65    }
66  
67    /**
68     * Equivalent to calling {@code flush(flushable, true)}, but with no
69     * {@code IOException} in the signature.
70     *
71     * @param flushable the {@code Flushable} object to be flushed.
72     */
73    public static void flushQuietly(Flushable flushable) {
74      try {
75        flush(flushable, true);
76      } catch (IOException e) {
77        logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
78      }
79    }
80  }